const Router = require('koa-router')
const path = require('path');
const fs = require('fs');
const router = new Router({
  //统一这是前缀
  prefix: '/api/v1/upload' 
})

const uploadimg = (ctx) => {
  let remotefilePath = null;
  if (ctx.request.files['file']) {
    // 创建可读流
    const reader = fs.createReadStream(ctx.request.files['file']['path']);
    
    let filePath = `${path.resolve(__dirname, '../../../static/images')}/${ctx.request.files['file']['name']}`;
    remotefilePath = `http://localhost:3000/images/${ctx.request.files['file']['name']}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);
  }
  return remotefilePath;
}

router.post('/uploadImg', async ctx => {
  const imgUrl = await uploadimg(ctx);
  if (imgUrl) {
    ctx.body = global.responseData(imgUrl,'文件上传成功')
  } else {
    ctx.body = global.responseData(imgUrl,'文件上传失败','579')
  }
  
})

module.exports = router